import pytesseract
from PIL import Image

"""
1.如果是白底图就不要进行灰度处理
2.其他颜色需要灰度处理
3.去除干扰"""


class authCode:
    def __init__(self, path):
        global img
        img = Image.open(path)
        img = img.convert('L')  # 转灰度
        # img.show()  图片已成灰色

    def start(self, threshold=120):  # 二值化
        pixdata = img.load()
        w, h = img.size
        # 遍历所有像素,大于阈值的为黑色 >>>>>>阈值默认120
        for y in range(h):
            for x in range(w):
                if pixdata[x, y] < threshold:  # 阈值是为了更好的区别数字与背景
                    pixdata[x, y] = 0
                else:
                    pixdata[x, y] = 255
        # 干扰处理
        now_pixdata = img.load()
        w, h = img.size
        for y in range(1, h - 1):
            for x in range(1, w - 1):
                count = 0
                if now_pixdata[x, y - 1] > 240:  # 下       # 大于240即为白色,干扰点上下左右都是白色>>>>>>>8领域算法
                    count = count + 1
                if now_pixdata[x, y + 1] > 240:  # 上
                    count = count + 1
                if now_pixdata[x - 1, y] > 240:  # 左
                    count = count + 1
                if now_pixdata[x + 1, y] > 240:  # 右
                    count = count + 1
                if now_pixdata[x - 1, y - 1] > 240:  # 左上
                    count = count + 1
                if now_pixdata[x - 1, y + 1] > 240:  # 左下
                    count = count + 1
                if now_pixdata[x + 1, y - 1] > 240:  # 右上
                    count = count + 1
                if now_pixdata[x + 1, y + 1] > 240:  # 右下
                    count = count + 1
                if count > 4:
                    now_pixdata[x, y] = 255
        return img


if __name__ == '__main__':
    img = authCode(r'E:\python_all\python_test\study_All\pillow_study\8069.jpg').start(threshold=170)
    result = pytesseract.image_to_string(img)
    print(result)
    # img.show()
